package com.pumpkin.web.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * (description)
 *
 * @author jinlong.liao on 2016/6/30
 */
@WebFilter(filterName = "contextFilter", urlPatterns = "/*")
public class ContextFilter implements Filter {

    private static final Logger LOG = LoggerFactory.getLogger(ContextFilter.class);

    private static final String SCHEME = "http://";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();

        String ctxPath = (String) session.getAttribute("ctx");
        if (ctxPath == null) {
            int serverPort = request.getServerPort();
            if (serverPort == 80) {
                ctxPath = SCHEME + request.getServerName() + request.getContextPath();
            } else {
                ctxPath = SCHEME + request.getServerName() + ":" + serverPort + request.getContextPath();
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("ctx path:{}", ctxPath);
            }

            session.setAttribute("ctx", ctxPath);
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
